const dayjs = require('dayjs');
const MongoClient = require('mongodb').MongoClient;
const urlProd = 'mongodb://taosha_user:apyl8XWP6LSW4JHs@101.35.6.34:27722/taosha';
const urlTest = 'mongodb://taosha_user:apyl8XWP6LSW4JHs@150.158.169.16:27017/taosha';

module.exports = {
  schedule: {
    cron: '0 0 4 * * ?',
    type: 'worker',
    env: ['pachong'],
    // immediate: true
  },

  async task(ctx) {
    let clientProd;
    let clientTest;

    try {
      clientProd = await MongoClient.connect(urlProd, {useNewUrlParser: true, useUnifiedTopology: true});
      const dbProd = clientProd.db('taosha');
      const CustomizeModelProd = dbProd.collection('customizes');
      const MessageModelProd = dbProd.collection('messages');
      const ReplyModelProd = dbProd.collection('replies');
      const TopicModelProd = dbProd.collection('topics');
      const TopicCollectModelProd = dbProd.collection('topic_collects');
      const UserModelProd = dbProd.collection('users');

      clientTest = await MongoClient.connect(urlTest, {useNewUrlParser: true, useUnifiedTopology: true});
      const dbTest = clientTest.db('taosha');
      const CustomizeModelTest = dbTest.collection('customizes');
      const MessageModelTest = dbTest.collection('messages');
      const ReplyModelTest = dbTest.collection('replies');
      const TopicModelTest = dbTest.collection('topics');
      const TopicCollectModelTest = dbTest.collection('topic_collects');
      const UserModelTest = dbTest.collection('users');


      const query = {createdAt: {$gt: dayjs().subtract(1, 'day').toDate()}};
      // const queryAll = {};
      const queryAll = query;

      const customizes = await CustomizeModelProd.find(queryAll).toArray();
      const messages = await MessageModelProd.find(queryAll).toArray();
      const replies = await ReplyModelProd.find(queryAll).toArray();
      const topics = await TopicModelProd.find(query).toArray();
      const topic_collects = await TopicCollectModelProd.find(queryAll).toArray();
      const users = await UserModelProd.find(queryAll).toArray();

      try {
        await CustomizeModelTest.insertMany(customizes, {ordered: false});
      } catch (e) {
      }
      try {
        await MessageModelTest.insertMany(messages, {ordered: false});
      } catch (e) {
      }
      try {
        await ReplyModelTest.insertMany(replies, {ordered: false});
      } catch (e) {
      }
      try {
        await TopicModelTest.insertMany(topics, {ordered: false});
      } catch (e) {
      }
      try {
        await TopicCollectModelTest.insertMany(topic_collects, {ordered: false});
      } catch (e) {
      }
      try {
        await UserModelTest.insertMany(users, {ordered: false});
      } catch (e) {
      }

      ctx.logger.info('最近24小时的数据同步成功...');
    } catch (e) {
      ctx.logger.error(e);
    } finally {
      if (clientProd) {
        clientProd.close();
      }
      if (clientTest) {
        clientTest.close();
      }
    }
  }

};